package edu.wpi.cs509.ui;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import java.util.Iterator;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;

import edu.wpi.cs509.common.exceptions.IllegalMove;
import edu.wpi.cs509.common.exceptions.InitialPlacementError;
import edu.wpi.cs509.common.exceptions.InvalidLocation;
import edu.wpi.cs509.common.exceptions.PieceNotFound;
import edu.wpi.cs509.common.exceptions.ServerUnreachable;
import edu.wpi.cs509.representation.Location;
import edu.wpi.cs509.representation.PlayerPiece;
import edu.wpi.cs509.representation.TeamColor;
import edu.wpi.cs509.ui.intfc.GameInterface;
import edu.wpi.cs509.ui.menu.GameWindowMenu;


@SuppressWarnings("serial")
public class GameWindowFrame extends JFrame implements WindowListener, ComponentListener {
	
	// the parent game window
	private GameWindow gameWindow;
	private GameWindowMenu menu;
	
	// the game board components
	private GameWindowFrameLayout layout;
	private GameBoardPanel board;
	private GameWindowControls controls;
	private Graveyard opponentGraveyard;	// always on top
	private Graveyard myGraveyard;			// always on bottom
	private GridTransform transform;

	// the game object
	private GameInterface game;
	private boolean switchflag = false;
	// Movement / Piece Placement State Information
	private PlayerPiece graveyardSelected;
	private GameBoardSquare squareSelected;
	private GameBoardSquare from;
	private GameBoardSquare to;
	//State variable for if the game's been started yet
	private boolean gameStarted = false;
	//Halt listeners if you're waiting for a response from the server
	private boolean haltListeners = false;
	
	/**
	 * Performs needed GameWindowFrame tasks when the game is started.
	 * @author ansawchu
	 *
	 */
	public void gameStarted() {
		gameStarted=true;
		if (!game.gameIsObserver()) {
			board.gameStarted(new MidGameEventHandler());
		}
		
		controls.displaySurrenderButton();
		controls.displayMoveButton();
	}
	
	/**
	 * Internal class to handle the Submit button (either for initial placement or mid-game).
	 * Uses the gameStarted state variable to decide which.
	 * 
	 *
	 */
	class SubmitHandler implements ActionListener {
		/** Listens for button click.
	    * @param e Event which triggered the handler
	    */
		
	    public void actionPerformed(ActionEvent e) {
	      // Print message on status line of window
	      System.out.println("Submit button has been clicked!");
	      if(!gameStarted){
	    	  try {
	    		  // Halt listeners and ready up
	    		  if(myGraveyard.getTotalPieceCount() == 0){
	    		      haltListeners(true);
	    		      game.ready();
	    		      controls.disableSubmitMoveButton();
	    		  } else {
			    		JOptionPane.showMessageDialog(myGraveyard, "Your ranks still swell with willing and able-bodied warriors!",
			    				"Coward!",JOptionPane.ERROR_MESSAGE);
	    		  }
	    	  }
	    	  catch (Exception e1){
	    		  e1.printStackTrace();
	    	  }
	      } else {
	    	  //Move a piece
	    	  if ( from != null && to != null) {
	    		  System.out.println("Moving piece!");
	    	      try{
	    	          game.move(transform.boardSquareToLocation(from), transform.boardSquareToLocation(to));
	    	          controls.disableSubmitMoveButton();
	    	          from.deselect();
	    	          from=null;
	    	          to.deselect();
	    	          to=null;
	    	      }
	    	      catch(IllegalMove e1){
	    		      Dialog.displayIllegalMoveDialog(e1);
	    	      } catch (ServerUnreachable e1) {
				    // TODO Auto-generated catch block
				    e1.printStackTrace();
			      }
	    	  } else {
	    		  Dialog.displayOneLocationSelectedDialog();
	    	  }
	      }
	    }
	    
	    /**
	     * Constructor for SubmitHandler.
	     */
	    public SubmitHandler() {
	    }
	}

	/**
	 * Internal class to handle the Surrender button (either for initial placement or mid-game).
	 * Uses the gameStarted state variable to decide which.
	 * 
	 *
	 */
	class SurrenderHandler implements ActionListener {
	    /** Listens for button click.
	    * @param e Event which triggered the handler
	    */
		
		private GameWindowFrame gwFrame;
		
	    public void actionPerformed(ActionEvent e) {
	      // Print message on status line of window
	      System.out.println("Surrender button has been clicked!");
	      
	      int ans = Dialog.displayQuitConfirmDialog();
	      if (ans == 0) {
	    	  gwFrame.dispose();
              try {
		          game.quit();
		      } catch (ServerUnreachable er) {
		          // catch block
			      Dialog.displayConnectionLostDialog();
		      }
	          gameWindow.quit();
	      }
	    }
	    
	    /**
	     * Constructor for SurrenderHandler.
	     */
	    public SurrenderHandler(GameWindowFrame gwFrame) {
	    	this.gwFrame = gwFrame;
	    }
	}

	
	
	
	//Moving
	/**
	 * Internal class to handle mouse clicks on the Graveyard. 
	 * Deals with the cases of clicking the graveyard before or after clicking on the game board.
	 * 
	 * Valid only for initial placement. Mouse clicks on the graveyard afterwards do nothing.
	 *
	 */
	private class GraveyardEventHandler implements GraveyardNotify {

		@Override
		public void pieceSelected( Graveyard graveyard, PlayerPiece piece ) {
			System.out.println("Piece selected");
			//If you've already picked a square on the gameboard, remove a piece.
			if(squareSelected!=null){
				try{
					System.out.println("Trying to remove a piece");
				    game.removePiece(transform.boardSquareToLocation(squareSelected));
				}
				catch(IllegalMove e){
					Dialog.displayIllegalMoveDialog(e);
				} catch(Exception e){
					e.printStackTrace();
				}
				graveyardSelected=null;
				graveyard.unselectAll();
				squareSelected.deselect();
				squareSelected=null;		
			//Otherwise just select the piece.
			} else {
				if(graveyard.getPieceCount(piece.getPieceType()) != 0){
				    graveyardSelected = piece;
				} else {
					graveyardSelected = null;
					graveyard.unselectAll();
		    		JOptionPane.showMessageDialog(graveyard, "You have already deployed all men of this rank.",
		    				"Error",JOptionPane.ERROR_MESSAGE);
				}
			}
		}
		
	}
	
	/**
	 * Internal class to handle mouse clicks on the GameBoard during mid-game only.
	 * 
	 *
	 */
	private class MidGameEventHandler implements GameBoardNotify {

		@Override
		public void pieceSelected(GameBoardSquare square) {
			if(!isListenersHalted()){
				if (square.isSelected()) {
					
					// either (1) deselecting 'from' square, deselect all
					//        (2) deselecting 'to' square, deselect to
					//        (3) selecting new square, change 'to' square
					
					System.out.println("UI: selected square selected");
					if (square == from) {
						from.deselect();
						if (to != null) to.deselect();
						from = to = null;
					} else if (square == to) {
						to.deselect();
						to = null;
					} else {
						to.deselect();
						to = square;
						to.select();
					}
				} else {  
					
					// unselected square chosen
					System.out.println("UI: Unselected Square selected");
					if (to != null) {
						to.deselect();
					}
					square.select();
					if (from==null) {
						from = square;
					} else {
						to = square;
					}
					
				}
			}
		}
		
	}
	/**
	 * Constructor for the GameWindowFrame. 
	 * Takes in a controller and a GameInterface (client game object).
	 * Creates the frame, and instantiates most of the panels inside the frame.
	 *
	 * @param gameWindow - The controller object.
	 * @param game - The client game object.
	 */
	public GameWindowFrame(GameWindow gameWindow, GameInterface game){
		
		this.gameWindow = gameWindow;
		this.game = game;
		
		boolean observer = game.gameIsObserver();
		
		// instantiate the transform object for this game instance
		this.transform = GridTransform.getIstance( game.getMyColor() );
		
		String opponentName = game.getOpponentName();
		if (opponentName == null) {
			opponentName = "Waiting for Player...";
		}
		
		// always display as RED vs BLUE
		if (game.getMyColor() == TeamColor.RED) {
			this.setTitle( game.getMyName() + " vs " + opponentName);
		} else {
			this.setTitle( opponentName + " vs " + game.getMyName());
		}
		
		// Create the temporary menu bar
		if (!observer) {
			menu = new GameWindowMenu(gameWindow);
			setJMenuBar(menu);
		}
		
		// Using GameWindowFrameLayout
		InitPlacementEventHandler initevent = new InitPlacementEventHandler();

		if (!observer) {
			board = new GameBoardPanel(10,10,initevent);
		} else {
			board = new GameBoardPanel(10,10,null);
		}
		board.setVisible(true);

		//Initialize event handlers for the buttons.
		SubmitHandler submitHandler = new SubmitHandler();
		SurrenderHandler surrenderHandler = new SurrenderHandler(this);
		
		if (!observer) {
			controls = new GameWindowControls( submitHandler, surrenderHandler );
		} else {
			controls = new GameWindowControls( null, null );
		}
		controls.setVisible(true);
				
		//Set up the opponent's graveyard.
		if (observer) {
			opponentGraveyard = new Graveyard( opponentName, game.getOpponentColor(), null, true);
		} else {
			if (game.obfuscatePieces()) {
				opponentGraveyard = new Graveyard( opponentName, game.getOpponentColor() );
			} else {
				opponentGraveyard = new Graveyard( opponentName, game.getOpponentColor(), null, false);
			}
		}
		opponentGraveyard.setVisible(true);
		
		if (!observer) {
			GraveyardEventHandler handler = new GraveyardEventHandler();
			myGraveyard = new Graveyard( game.getMyName(), game.getMyColor(), handler, false);
		} else {
			myGraveyard = new Graveyard( game.getMyName(), game.getMyColor(), null, true);
		}
		myGraveyard.setVisible(true);
		
		//Assemble the game screen
		Container contentArea = this.getContentPane();
		layout = new GameWindowFrameLayout(board, opponentGraveyard, myGraveyard, controls);
		contentArea.setLayout( layout );
		contentArea.add( board );
		contentArea.add(myGraveyard);
		contentArea.add(controls);
		contentArea.add(opponentGraveyard);
		contentArea.setVisible(true);
		addComponentListener(this);
		pack();
		setVisible(true);
		
		setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
		addWindowListener( this );
		
		
		//Initialize the game board squares. Mainly to draw where
		//the opponent has already placed pieces.  Must occur after the 
		// graveyard is initialized since the piece count needs to be set.
		PlayerPiece piece;
		GameBoardSquare square;
		for(int i=0;i<100;i++) {
			try {
				square = board.getGameBoardSquare(i);
				piece = game.getPiece(transform.boardSquareToLocation(square));
				if (piece.getColor() == game.getOpponentColor()) {
					square.addPiece(piece);
					int count = opponentGraveyard.getPieceCount(piece.getPieceType());
					--count;
					opponentGraveyard.setPieceCount(piece.getPieceType(), count);
				}
			} catch (PieceNotFound e) { 
				// this is ok
			}
		}

	}	

	/**
	 * Getter to return the game board.
	 * 
	 *
	 */
	public GameBoardPanel getGamePanel(){
		return this.board;
	}
	/**
	 * Internal class to handle mouse clicks on the GameBoard during initial placement only.
	 * 
	 *
	 */
	private class InitPlacementEventHandler implements GameBoardNotify {
		public void pieceSelected(GameBoardSquare square){
			if(!isListenersHalted()){
				
				//If you've picked something from the graveyard already,
				//add that piece here.
				if (graveyardSelected!=null){
					System.out.println("Put piece");
					myGraveyard.unselectAll();
					try{
						game.placePiece(transform.boardSquareToLocation(square), graveyardSelected);
					}
					catch(IllegalMove e){
						Dialog.displayIllegalMoveDialog(e);
					} catch (InvalidLocation e) {
						// TODO Auto-generated catch block
						Dialog.displayInvalidLocationDialog(e);
					}catch (ServerUnreachable e) {
						// TODO Auto-generated catch block
					}
					myGraveyard.unselectAll();
					graveyardSelected=null;
					if(squareSelected != null){
						squareSelected.deselect();
						squareSelected=null;
					}

				} else if (squareSelected!=null) {
	
					// two squares have been selected -- determine what to do based on whether there
					// are pieces on the squares
					
					//If you're picking the same square twice, deselect it
					if (squareSelected==square){
						System.out.println("Deselect");
						squareSelected.deselect();
						squareSelected=null;
						return;
					}
					
					try {

						// 
						PlayerPiece pFrom, pTo;
						try {
							pFrom = game.getPiece(transform.boardSquareToLocation(squareSelected));
						} catch(PieceNotFound p1) {
							pFrom = null;
						} 
						try {
							pTo = game.getPiece(transform.boardSquareToLocation(square));
						} catch(PieceNotFound p2) {
							pTo = null;
						} 
						
						if ((pFrom != null) && (pTo != null)) {
							
							// both squares have pieces, swap them
							System.out.println("Switch pieces");

						    game.removePiece(transform.boardSquareToLocation(square));
						    game.removePiece(transform.boardSquareToLocation(squareSelected));
						    
						    // FIXME
						    // due to a race condition where the client game has the pieces on the squares
						    // and the server has not responded yet, we can't immediately swap the pieces
						    // and call placePiece().  The solution for this is complicated so we'll 
						    // defer
						    
							// Place the piece as though it came from the graveyard
						    // pFrom.setLocation( new Location() );
						    // game.placePiece(transform.boardSquareToLocation(square), pFrom);

							// Place the piece as though it came from the graveyard
						    // pTo.setLocation( new Location() );
						    // game.placePiece(transform.boardSquareToLocation(squareSelected), pTo);
						    
							squareSelected.deselect();
						    squareSelected = null;
						    
						} else if ((pFrom != null) && (pTo == null)) {
							
							// The from square has a piece, the 'to' square is empty.  Move the piece.
							System.out.println("Move piece");
							
							game.removePiece(transform.boardSquareToLocation(squareSelected));
							
							// Place the piece as though it came from the graveyard
							pFrom.setLocation(new Location());
							game.placePiece(transform.boardSquareToLocation(square), pFrom);
						    
							squareSelected.deselect();
						    squareSelected = null;
						    
						} else if ((pFrom == null) && (pTo == null)) {
							
							// both squares are empty -- treat as a change of selection to the new square
							System.out.println("Change selection");
						    
							squareSelected.deselect();
						    squareSelected = square;
						    square.select();
						}
					
					} catch(IllegalMove e){
						Dialog.displayIllegalMoveDialog(e);
						squareSelected.deselect();
						squareSelected=null;
					} catch(InvalidLocation e){
						Dialog.displayInvalidLocationDialog(e);
						squareSelected.deselect();
						squareSelected=null;
					} catch(Exception e){
						e.printStackTrace();
						squareSelected.deselect();
						squareSelected=null;
					}
				
				} else {
					//Otherwise just select that square.

					System.out.println("Pick square");
					squareSelected=square;
					square.select();
				}
			}
		}
	}
	/**
	 * TODO No clue.
	 * 
	 *
	 */
	@Override
	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}
	/**
	 * TODO No clue.
	 * 
	 *
	 */
	@Override
	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}
	/**
	 * Window closing handling. Redirects window closing to the quit button handler.
	 * 
	 *
	 */
	@Override
	public void windowClosing(WindowEvent arg0) {
		int ans = Dialog.displayQuitConfirmDialog();
		if (ans == 0) {
			try {
				game.quit();
			} catch (ServerUnreachable e) {
				// Nothing we can do about this...
			}
			this.dispose();
		}
		gameWindow.quit();
	}
	/**
	 * TODO No clue.
	 * 
	 *
	 */
	@Override
	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}
	/**
	 * TODO No clue.
	 * 
	 *
	 */
	@Override
	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}
	/**
	 * TODO No clue.
	 * 
	 *
	 */
	@Override
	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}
	/**
	 * TODO No clue.
	 * 
	 *
	 */
	@Override
	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * Removes a piece from the graveyard and places it on the specified board square.
	 * The board square must be transformed from the provided game board Location object.
	 * @param piece - the player piece
	 * @param location - the board square
	 */
	public void placePiece(PlayerPiece piece, Location location) throws InitialPlacementError {
	
		Graveyard g;
		
		// check whose piece is being placed
		if (piece.getColor() == game.getMyColor()) {
			g = myGraveyard;
		} else {
			g = opponentGraveyard;
		}
		
		// check the count for availability
		int count = g.getPieceCount(piece.getPieceType());
		if (count <= 0) {
			throw new InitialPlacementError("There are no "+piece.getName()+" pieces in the graveyard");
		}
			
		// remove from the graveyard
		g.setPieceCount(piece.getPieceType(), --count);
			
		// draw the piece on the correct board location
		int index = transform.locationToBoardSquare( location );
		GameBoardSquare square = gameWindow.getGameWindowFrame().getGamePanel().getGameBoardSquare( index );
		square.addPiece(piece);
		
		// submit is only allowed once all piecces in the graveyard have been placed
		if (g.getTotalPieceCount() == 0) {
			controls.enableSubmitMoveButton();
		} else {
			System.out.println("Total Piece count is: " + g.getTotalPieceCount());
			// The change in logic is this, because placePiece can come in from either side
			// and the graveyard may not know where this is coming from, the submit should
			// not be touched unless it is for that players side. It can be debated that this
			// would be fixed if under obfuscation the graveyard would also be obfuscated and
			// then this would work, however the status of the button should be determined
			// by that sides status and not by an event from the opponent like updating the
			// graveyard.
			if ( piece.getColor() == game.getMyColor() ) {
			    controls.disableSubmitMoveButton();
			}
		}
		
	}

	/**
	 * When the opponent indicates ready, the obfuscated graveyard should
	 * be replaced by a visible graveyard. 
	 */
	public void opponentReady() {
		
		// no changing the graveyard if this is an observer
		if (game.gameIsObserver()) {
			return;
		}
		
		// change the opponent graveyard, which has been obfuscated during initial setup
		// to display the pieces all with 0 starting count
		Container contentArea = this.getContentPane();
		Graveyard newOpponentGraveyard;
		
		// hide the old one
		opponentGraveyard.setVisible(false);
		contentArea.remove(opponentGraveyard);
		
		// create the new one
		GraveyardEventHandler handler = new GraveyardEventHandler();		
		newOpponentGraveyard = new Graveyard( game.getOpponentName(), game.getOpponentColor(), handler, true);
		
		// set new graveyard
		opponentGraveyard = newOpponentGraveyard;
		
		// tell the frame about the new one
		layout.setNewOpponentGraveyard(newOpponentGraveyard);
		contentArea.add(newOpponentGraveyard);
		newOpponentGraveyard.setVisible(true);
		
		validate();
	}

	/**
	 * When the opponent joins, the graveyard name must be updated and
	 * the frame window title
	 */
	public void opponentJoined() {
		
		opponentGraveyard.setPlayerName( game.getOpponentName() );
		
		if (game.getMyColor() == TeamColor.RED) {
			this.setTitle( game.getMyName() + " vs " + game.getOpponentName());
		} else {
			this.setTitle( game.getOpponentName() + " vs " + game.getMyName());
		}
	}

	
	/**
	 * DEBUG METHOD ONLY unless you really don't care if you win or lose.
	 * This method will allow you to place all your remaining pieces randomly on the board.
	 * 
	 *
	 */
	public void quickPlaceRemainingPieces() {
		
		List<PlayerPiece> myPieces = myGraveyard.getRemainingPieces();
		Iterator<PlayerPiece> itr = myPieces.iterator();
		PlayerPiece piece;
		
		// fill in all open board squares on bottom
		for (int row=6; row<10; row++) {
			for (int col=0; col<10; col++) {
				try {
					if (game.isSquareEmpty(transform.boardSquareToLocation(row,col))) {
						piece = itr.next();
						game.placePiece(transform.boardSquareToLocation(row,col), piece);
						this.repaint();
					}
				} catch (IllegalMove e) {
					// TODO Auto-generated catch block
					Dialog.displayIllegalMoveDialog(e);
				} catch (InvalidLocation e) {
					// TODO Auto-generated catch block
					Dialog.displayInvalidLocationDialog(e);
				} catch (ServerUnreachable e) {
					// TODO Auto-generated catch block
				}
			}
		}
		
	}

	/**
	 *  setMyTurn should be called to indicate to the player that it is their turn to
	 *  move.  This is currently done by blinking the player's name in their
	 *  graveyard, and by enabling the Move button in their control pane.
	 *  
	 */
	public void setMyTurn() {
		myGraveyard.setMyTurn();
		controls.enableSubmitMoveButton();
	}
	
	/**
	 * clearMyTurn should be called after the player has submitted their move to the
	 * server.  This clears their highlighted name in the graveyard, and disables 
	 * their Move button to prevent duplicate move submissions.
	 */
	public void clearMyTurn() {
		myGraveyard.clearMyTurn();
		controls.disableSubmitMoveButton();
	}
	
	/**
	 * Move piece will update the specified piece, removing it from the 'from' location
	 * and placing it on the 'to' location.
	 * 
	 * @note The 'to' and 'from' locations must always be valid gameboard locations and
	 * cannot be the graveyard
	 * 
	 * @param piece - the piece to move (including color)
	 * @param from - the location the piece is moving from
	 * @param to - the location the piece is moving to
	 */
	public void movePiece( PlayerPiece piece, Location from, Location to ) {
		
		// no boneyard to/from location
		if (from.isInBoneyard() || to.isInBoneyard()) {
			System.out.println("Cannot move a piece 'to' or 'from' the graveyard.");
			return;
		}
		
		board.movePiece( piece, transform.locationToBoardSquare(from),transform.locationToBoardSquare(to));
		repaint();
	}
	
	/**
	 * Method to remove a piece from the board (and place it back in the appropriate graveyard).
	 * 
	 * @param piece - the piece on the board to be removed
 	 *
	 */
	public void removePiece(PlayerPiece piece, Location from) {
		
		// ignore removes from graveyard
		if (from.isInBoneyard()) {
			return;
		}
		
		board.removePiece(transform.locationToBoardSquare(from));
		Graveyard g;
		if (piece.getColor() == game.getMyColor()) {
			g = myGraveyard;
		} else {
			g = opponentGraveyard;
		}
		int count = g.getPieceCount(piece.getPieceType());
		g.setPieceCount(piece.getPieceType(),count+1);
		if(squareSelected != null && !switchflag) {
			squareSelected.deselect();
			squareSelected=null;
		}
	}

	/**
	 * Getter method to determine if your listeners are turned off
	 * (if you're blocking for a call return)
	 * 
	 * 
	 */
	public boolean isListenersHalted() {
		return haltListeners;
	}

	/**
	 * Halts listeners (i.e. if you just sent a call out to the servers)
	 * 
	 *
	 */
	public void haltListeners(boolean haltListeners) {
		this.haltListeners = haltListeners;
	}

	/**
	 * Returns the player piece to the appropriate graveyard
	 * @param defender
	 */
	public void putInGraveyard(PlayerPiece piece) {
		System.out.println("Piece going in graveyard");
		// TODO Auto-generated method stub
		if (piece.getColor() == myGraveyard.getColor()) {
			int count = myGraveyard.getPieceCount(piece.getPieceType());
			count++;
			myGraveyard.setPieceCount(piece.getPieceType(),count);
		} else {
			System.out.println("Adding opponent's piece to graveyard"); 
			int count = opponentGraveyard.getPieceCount(piece.getPieceType());
			count++;
			opponentGraveyard.setPieceCount(piece.getPieceType(),count);
		}
			
	}

	/**
	 * Returns a board square for a given location.
	 * 
	 * @param loc - The location in question
	 */
	public GameBoardSquare getBoardSquare(Location loc) {
		GameBoardSquare square = (GameBoardSquare) board.getComponent( transform.locationToBoardSquare(loc));
		return square;
	}

	private int countEnemyPieces(){
		int enemyPieces = 0;
		for(int i=0;i<40;i++){
			//count the piece if it's found
			try {
			    game.getPiece(transform.boardSquareToLocation((GameBoardSquare) board.getComponent(i)));
			    i++;
			}
			//do nothing if PieceNotFound
			catch (PieceNotFound e){}
		}
		return enemyPieces;
	}
	
	/**
	 * From Component Listener
	 */
	@Override
	public void componentHidden(ComponentEvent e) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * From Component Listener
	 */
	@Override
	public void componentMoved(ComponentEvent e) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * From Component Listener
	 */
	@Override
	public void componentResized(ComponentEvent e) {
		// FIXME
		//setSize( getContentPane().getSize() );
	}

	/**
	 * From Component Listener
	 */
	@Override
	public void componentShown(ComponentEvent e) {
		// TODO Auto-generated method stub
		
	}
	/**
	 * Method to redraw the entire board.
	 * Updates the piece that's in each square and repaints.
	 * 
	 */
	public void redraw(){
		//Reset the counts in the boneyards, we'll fix them later
		/*
		if(!gameStarted){
			myGraveyard.resetPieceCounts();
			opponentGraveyard.resetPieceCounts();
		}
		*/
		
		for(int i=0;i<100;i++){
	
			GameBoardSquare square = board.getGameBoardSquare(i);
			//Add whatever is at that location to each UI square.
			//addPiece will repaint the square.
			try {
				PlayerPiece thisPiece = game.getPiece(transform.boardSquareToLocation(square));
				square.addPiece(thisPiece);
				/*
				if (thisPiece != null && !gameStarted){
					//Determine if you're updating your graveyard or your opponent's
					Graveyard g = ((thisPiece.getColor() == game.getMyColor()) ? myGraveyard : opponentGraveyard);
					GraveyardPlot plot = g.getGraveyardPlot(thisPiece.getPieceType());
					if (plot != null){
						g.setPieceCount( thisPiece.getPieceType(), g.getPieceCount(thisPiece.getPieceType())-1);
						plot.repaint();
					}
				}
				*/
			} catch (PieceNotFound e) {
				square.addPiece(null);
			}
		}
		/*
		myGraveyard.repaint();
		opponentGraveyard.repaint();
		*/
		repaint();
	}
    public void changeQuitButton(){
    	controls.displayQuitButton();
    }
}
